#!/usr/bin/env node

/**
 * MCP (Multi-Component Project) 工具
 * 用于自动启动和管理项目的多个组件（前端、后端等）
 */

const fs = require('fs');
const path = require('path');
const { exec, execSync, spawn } = require('child_process');
const os = require('os');
const http = require('http');
const https = require('https');

// 全局配置
let config = null;
let logger = null;
let services = {};
let isExiting = false;

/**
 * 初始化日志系统 - 使用Node.js内置模块
 */
function initLogger(logLevel, logFilePath) {
  const levels = { debug: 0, info: 1, warn: 2, error: 3 };
  const currentLevel = levels[logLevel] || levels.info;
  
  // 增强的颜色代码
  const colors = {
    reset: '\x1b[0m',
    gray: '\x1b[90m',
    blue: '\x1b[34m',
    yellow: '\x1b[33m',
    red: '\x1b[31m',
    green: '\x1b[32m',
    cyan: '\x1b[36m'
  };
  
  // 主日志文件流
  const logFileStream = logFilePath ? fs.createWriteStream(logFilePath, { flags: 'a' }) : null;
  
  // 错误日志文件路径
  const errorLogPath = 'mcp-error.log';
  
  // 写入错误日志文件的函数
  const writeErrorLog = (message) => {
    try {
      const timestamp = new Date().toISOString();
      fs.appendFileSync(
        errorLogPath,
        `[${timestamp}] [ERROR] ${message}\n`,
        'utf8'
      );
    } catch (err) {
      // 防止日志写入失败导致程序崩溃
      console.error('Failed to write to error log:', err.message);
    }
  };
  
  const log = {
    debug: (message) => {
      if (currentLevel <= levels.debug) {
        const timestamp = new Date().toISOString();
        console.log(`${colors.cyan}[${timestamp}] [DEBUG] ${message}${colors.reset}`);
        logFileStream?.write(`[${timestamp}] [DEBUG] ${message}\n`);
      }
    },
    info: (message) => {
      if (currentLevel <= levels.info) {
        const timestamp = new Date().toISOString();
        console.log(`${colors.blue}[${timestamp}] [INFO] ${message}${colors.reset}`);
        logFileStream?.write(`[${timestamp}] [INFO] ${message}\n`);
      }
    },
    warn: (message) => {
      if (currentLevel <= levels.warn) {
        const timestamp = new Date().toISOString();
        console.log(`${colors.yellow}[${timestamp}] [WARN] ${message}${colors.reset}`);
        logFileStream?.write(`[${timestamp}] [WARN] ${message}\n`);
      }
    },
    error: (message) => {
      if (currentLevel <= levels.error) {
        const timestamp = new Date().toISOString();
        console.error(`${colors.red}[${timestamp}] [ERROR] ${message}${colors.reset}`);
        logFileStream?.write(`[${timestamp}] [ERROR] ${message}\n`);
        // 错误级别同时写入错误日志文件
        writeErrorLog(message);
      }
    },
    success: (message) => {
      const timestamp = new Date().toISOString();
      console.log(`${colors.green}[${timestamp}] [SUCCESS] ${message}${colors.reset}`);
      logFileStream?.write(`[${timestamp}] [SUCCESS] ${message}\n`);
    },
    print: (message) => {
      const timestamp = new Date().toISOString();
      console.log(`[${timestamp}] ${message}`);
      logFileStream?.write(`[${timestamp}] ${message}\n`);
    },
    // 增强错误处理方法
    handleError: (error, context = 'Unknown error') => {
      const errorMessage = typeof error === 'string' ? error : error.message || 'Unknown error';
      const fullMessage = `${context}: ${errorMessage}`;
      
      // 记录堆栈信息
      if (error instanceof Error && error.stack) {
        const stackTrace = error.stack;
        logFileStream?.write(`[${new Date().toISOString()}] [ERROR-STACK] ${stackTrace}\n`);
        writeErrorLog(`${fullMessage}\nStack: ${stackTrace}`);
      } else {
        writeErrorLog(fullMessage);
      }
      
      // 输出到控制台
      log.error(fullMessage);
    }
  };
  
  return log;
}

/**
 * 加载配置文件
 * @param {string} configPath - 配置文件路径
 * @returns {Object} 配置对象
 */
function loadConfig(configPath) {
  try {
    const defaultConfigPath = path.join(process.cwd(), '.mcp.js');
    const finalConfigPath = configPath || defaultConfigPath;
    
    // 默认配置
    const defaultConfig = {
      global: {
        buildBeforeStart: false,
        openBrowserOnStart: true,
        logLevel: 'info'
      },
      backend: {
        enabled: true,
        type: 'java',
        port: 8081,
        startCommand: 'java -jar target/ai-platform-backend-1.0.0.jar --server.port=8081',
        startTimeout: 30000,
        healthCheckPath: '/actuator/health'
      },
      frontend: {
        enabled: true,
        type: 'npm',
        port: 2180,
        startCommand: 'npm run dev',
        buildCommand: 'npm run build',
        startTimeout: 15000
      },
      logging: {
        level: 'info',
        filePath: null
      }
    };
    
    if (!fs.existsSync(finalConfigPath)) {
      console.log(`配置文件不存在: ${finalConfigPath}`);
      console.log('使用默认配置');
      return defaultConfig;
    }
    
    try {
      const customConfig = require(finalConfigPath);
      const mergedConfig = {...defaultConfig, ...customConfig};
      // 只有在logger初始化后才使用它
      if (logger) {
        logger.info(`已加载配置文件: ${finalConfigPath}`);
      }
      return mergedConfig;
    } catch (error) {
      console.error(`${'\x1b[31m'}错误: 配置文件解析失败: ${error.message}${'\x1b[0m'}`);
      console.log('使用默认配置');
      return defaultConfig;
    }
  } catch (error) {
    console.error(`加载配置时出错: ${error.message}`);
    return {
      global: {
        buildBeforeStart: false,
        openBrowserOnStart: true,
        logLevel: 'info'
      },
      backend: {
        enabled: true,
        type: 'java',
        port: 8081,
        startCommand: 'java -jar target/ai-platform-backend-1.0.0.jar --server.port=8081',
        startTimeout: 30000,
        healthCheckPath: '/actuator/health'
      },
      frontend: {
        enabled: true,
        type: 'npm',
        port: 2180,
        startCommand: 'npm run dev',
        buildCommand: 'npm run build',
        startTimeout: 15000
      },
      logging: {
        level: 'info',
        filePath: null
      }
    };
  }
}

/**
 * 使用Node.js内置http模块发送GET请求
 */
async function httpGet(url, options = {}) {
  return new Promise((resolve, reject) => {
    const timeout = options.timeout || 3000;
    const headers = options.headers || {};
    
    // 解析URL
    const parsedUrl = new URL(url);
    const protocol = parsedUrl.protocol === 'https:' ? https : http;
    
    const requestOptions = {
      hostname: parsedUrl.hostname,
      port: parsedUrl.port,
      path: parsedUrl.pathname + parsedUrl.search,
      method: 'GET',
      headers: headers,
      timeout: timeout
    };
    
    // 设置最大重定向次数
    const maxRedirects = options.maxRedirects !== undefined ? options.maxRedirects : 2;
    let redirectCount = 0;
    
    const sendRequest = (opts) => {
      const req = protocol.request(opts, (res) => {
        let data = '';
        
        res.on('data', (chunk) => {
          data += chunk;
        });
        
        res.on('end', () => {
          // 处理重定向
          if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location && redirectCount < maxRedirects) {
            redirectCount++;
            const redirectUrl = new URL(res.headers.location, url).href;
            logger.debug(`重定向到: ${redirectUrl}`);
            
            const redirectParsedUrl = new URL(redirectUrl);
            const redirectProtocol = redirectParsedUrl.protocol === 'https:' ? https : http;
            
            sendRequest({
              hostname: redirectParsedUrl.hostname,
              port: redirectParsedUrl.port,
              path: redirectParsedUrl.pathname + redirectParsedUrl.search,
              method: 'GET',
              headers: headers,
              timeout: timeout
            });
          } else {
            resolve({
              status: res.statusCode,
              data: data,
              headers: res.headers
            });
          }
        });
      });
      
      req.on('timeout', () => {
        req.destroy();
        reject(new Error('请求超时'));
      });
      
      req.on('error', (error) => {
        reject(error);
      });
      
      req.end();
    };
    
    sendRequest(requestOptions);
  });
}

/**
 * 检查后端服务健康状态
 */
async function checkBackendHealth() {
  const { port, healthCheckPath } = config.backend;
  
  // 尝试不同的健康检查路径
  const healthPaths = [
    healthCheckPath,  // 配置的路径
    '/actuator/health', // 标准Spring Boot Actuator路径
    '/health' // 可能的自定义健康检查路径
  ];
  
  // 尝试所有可能的健康检查路径
  for (const path of healthPaths) {
    const url = `http://localhost:${port}${path}`;
    
    try {
      logger.debug(`尝试后端健康检查: ${url}`);
      const response = await httpGet(url, {
        timeout: 3000,
        headers: { 'Accept': 'application/json' },
        maxRedirects: 0
      });
      
      if (response.status === 200) {
        // 尝试解析JSON
        let data = {};
        try {
          data = JSON.parse(response.data);
        } catch (e) {
          logger.debug(`无法解析JSON响应: ${e.message}`);
        }
        
        // 检查多种可能的健康状态格式
        const isHealthy = 
          data.status === 'UP' ||
          data.health === 'UP' ||
          (data.status && data.status.toLowerCase() === 'up') ||
          (data.health && data.health.toLowerCase() === 'up') ||
          Object.keys(data).length > 0;
        
        if (isHealthy) {
          logger.debug(`后端健康检查成功: ${url}`);
          return true;
        }
      }
    } catch (error) {
      logger.debug(`后端健康检查失败 [${url}]: ${error.message}`);
    }
  }
  
  // 尝试根路径
  try {
    const response = await httpGet(`http://localhost:${port}/`, {
      timeout: 3000,
      maxRedirects: 0
    });
    
    if (response.status >= 200 && response.status < 400) {
      logger.debug(`后端根路径检查成功，端口 ${port} 上有服务运行`);
      return true;
    }
    // 处理重定向错误
    else if (response.status === 301 || response.status === 302) {
      logger.debug(`后端根路径重定向，端口 ${port} 上有服务运行`);
      return true;
    }
  } catch (error) {
    logger.debug(`后端根路径检查失败: ${error.message}`);
  }
  
  return false;
}

/**
 * 检查前端服务健康状态
 */
async function checkFrontendHealth() {
  const { port, healthCheckPath } = config.frontend;
  
  // 尝试不同的健康检查路径
  const healthPaths = [
    healthCheckPath,  // 配置的路径
    '/',              // 根路径
    '/index.html'     // 可能的入口文件
  ];
  
  // 尝试所有可能的健康检查路径
  for (const path of healthPaths) {
    const url = `http://localhost:${port}${path}`;
    
    try {
      logger.debug(`尝试前端健康检查: ${url}`);
      const response = await httpGet(url, {
        timeout: 3000,
        maxRedirects: 0
      });
      
      if (response.status >= 200 && response.status < 400) {
        logger.debug(`前端健康检查成功: ${url}`);
        return true;
      }
    } catch (error) {
      logger.debug(`前端健康检查失败 [${url}]: ${error.message}`);
    }
  }
  
  return false;
}

/**
 * 启动服务
 * @param {string} serviceType - 服务类型 ('backend' 或 'frontend')
 * @param {number} maxRetries - 最大重试次数
 * @returns {Promise<boolean>} 服务是否成功启动
 */
async function startService(serviceType, maxRetries = 2) {
  const serviceConfig = serviceType === 'backend' ? config.backend : config.frontend;
  const { name, startCommand, workingDir, port, startupTimeout } = serviceConfig;
  
  logger.info(`正在启动 ${name}...`);
  
  let retries = 0;
  let lastError = null;
  
  while (retries <= maxRetries) {
    try {
      const cwd = path.isAbsolute(workingDir) ? workingDir : path.join(config.projectRoot, workingDir);
      
      // 根据操作系统选择shell
      const shell = os.platform() === 'win32' ? 'cmd.exe' : '/bin/bash';
      const shellArgs = os.platform() === 'win32' ? ['/c'] : ['-c'];
      
      // 确保前一个进程已停止
      if (services[serviceType]) {
        try {
          services[serviceType].kill('SIGINT');
          await new Promise(resolve => setTimeout(resolve, 1000));
        } catch (killError) {
          logger.error(`停止 ${name} 进程失败: ${killError.message}`);
        }
      }
      
      // 启动服务进程
      const process = spawn(startCommand, {
        shell: true,
        cwd,
        stdio: ['ignore', 'pipe', 'pipe']
      });
      
      // 输出服务日志
      process.stdout.on('data', (data) => {
        const logData = data.toString().trim();
        if (logData) {
          console.log(`${'\x1b[32m'}[${name}]${'\x1b[0m'} ${logData}`);
        }
      });
      
      process.stderr.on('data', (data) => {
        const logData = data.toString().trim();
        if (logData) {
          console.error(`${'\x1b[31m'}[${name} ERROR]${'\x1b[0m'} ${logData}`);
        }
      });
      
      process.on('exit', (code) => {
        if (isExiting) return;
        
        logger.error(`${name} 意外退出，退出码: ${code}`);
        
        // 如果后端服务退出，前端服务也应该停止
        if (serviceType === 'backend' && services.frontend) {
          logger.info(`正在停止 ${config.frontend.name}...`);
          services.frontend.kill();
        }
        
        // 如果不是故意退出，显示错误信息
        if (!isExiting) {
          logger.error('服务启动失败，请检查日志和配置');
          // 使用更安全的退出方式，避免process.exit兼容性问题
          try {
            process.exit && process.exit(1);
          } catch (e) {
            console.error('无法正常退出进程:', e.message);
            setTimeout(() => {}, 1000); // 给日志一些时间输出
          }
        }
      });
      
      // 保存服务进程引用
      services[serviceType] = process;
      
      // 等待服务启动完成
      const started = await waitForService(serviceType, startupTimeout);
      
      if (started) {
        logger.info(`${name} 启动成功`);
        return true;
      } else {
        throw new Error(`${name} 启动超时`);
      }
    } catch (error) {
      lastError = error;
      retries++;
      
      if (retries <= maxRetries) {
        logger.warn(`启动 ${name} 失败 (${retries}/${maxRetries} 次重试): ${error.message}`);
        logger.info('正在尝试重新启动...');
        await new Promise(resolve => setTimeout(resolve, 3000)); // 等待3秒后重试
      } else {
        logger.error(`启动 ${name} 失败，已达到最大重试次数`);
        logger.handleError(error, `${name} 启动失败`);
        throw error;
      }
    }
  }
  
  throw lastError || new Error(`${name} 启动失败，未知错误`);
}

/**
 * 等待服务启动完成
 */
async function waitForService(serviceType, timeout) {
  const serviceConfig = serviceType === 'backend' ? config.backend : config.frontend;
  const { name, port } = serviceConfig;
  
  logger.info(`等待 ${name} 启动完成 (端口 ${port})...`);
  
  const startTime = Date.now();
  const healthCheckFn = serviceType === 'backend' ? checkBackendHealth : checkFrontendHealth;
  
  // 定期检查服务健康状态
  while (Date.now() - startTime < timeout * 1000) {
    try {
      const isHealthy = await healthCheckFn();
      if (isHealthy) {
        logger.info(`${name} 启动成功，端口 ${port}`);
        return true;
      }
    } catch (error) {
      logger.debug(`服务检查失败: ${error.message}`);
    }
    
    // 等待1秒后再次检查
    await new Promise(resolve => setTimeout(resolve, 1000));
  }
  
  logger.error(`${name} 启动超时，未在 ${timeout} 秒内响应`);
  return false;
}

/**
 * 构建项目
 */
function buildProject() {
  logger.info('开始构建项目...');
  
  // 构建后端
  if (config.backend.buildCommand) {
    logger.info(`正在构建 ${config.backend.name}...`);
    const cwd = path.join(config.projectRoot, config.backend.workingDir);
    try {
      execSync(config.backend.buildCommand, { cwd, stdio: 'inherit' });
      logger.info(`${config.backend.name} 构建成功`);
    } catch (error) {
      logger.error(`${config.backend.name} 构建失败`);
      process.exit(1);
    }
  }
  
  // 构建前端
  if (config.frontend.buildCommand) {
    logger.info(`正在构建 ${config.frontend.name}...`);
    const cwd = path.join(config.projectRoot, config.frontend.workingDir);
    try {
      execSync(config.frontend.buildCommand, { cwd, stdio: 'inherit' });
      logger.info(`${config.frontend.name} 构建成功`);
    } catch (error) {
      logger.error(`${config.frontend.name} 构建失败`);
      process.exit(1);
    }
  }
  
  logger.info('项目构建完成');
}

/**
 * 停止所有服务
 */
function stopAllServices() {
  try {
    logger.info('============================================');
    logger.info('正在停止所有服务...');
    logger.info('============================================');
    
    // 设置退出标志，防止服务意外退出时触发额外的错误处理
    isExiting = true;
    
    const servicesToStop = [];
    
    // 收集所有需要停止的服务
    if (services.frontend) {
      servicesToStop.push({ type: 'frontend', process: services.frontend, name: config.frontend.name });
    }
    if (services.backend) {
      servicesToStop.push({ type: 'backend', process: services.backend, name: config.backend.name });
    }
    
    // 按顺序停止服务（先前端后后端）
    servicesToStop.forEach(service => {
      try {
        logger.info(`正在停止 ${service.name}...`);
        
        // 先尝试优雅停止
        try {
          service.process.kill('SIGINT');
        } catch (e) {
          // 如果优雅停止失败，尝试强制停止
          logger.warn(`优雅停止 ${service.name} 失败，尝试强制停止: ${e.message}`);
          service.process.kill('SIGKILL');
        }
        
        // 清理引用
        services[service.type] = null;
        logger.info(`${service.name} 已停止`);
      } catch (error) {
        logger.error(`停止 ${service.name} 时出错: ${error.message}`);
        logger.debug(`服务类型: ${service.type}, PID: ${service.process.pid}`);
      }
    });
    
    // 如果没有服务需要停止
    if (servicesToStop.length === 0) {
      logger.info('没有正在运行的服务');
    }
    
    // 清理资源
    cleanupResources();
    
    logger.info('============================================');
    logger.info('所有服务已停止');
    logger.info('============================================');
  } catch (error) {
    console.error('停止服务时发生错误:', error.message);
    // 即使出错，也要确保设置退出标志
    isExiting = true;
    try {
      cleanupResources();
    } catch (cleanupError) {
      console.error('清理资源时出错:', cleanupError.message);
    }
  }
}

/**
 * 清理资源
 */
function cleanupResources() {
  try {
    // 清理事件监听器
    const events = ['SIGINT', 'SIGTERM'];
    events.forEach(event => {
      process.removeAllListeners(event);
    });
    
    logger.debug('资源清理完成');
  } catch (error) {
    console.error('清理资源时出错:', error.message);
  }
}

/**
 * 打开浏览器 - 使用Node.js内置child_process
 */
async function openBrowser() {
  if (!config.global.openBrowserOnStart) return;
  
  let url = config.global.openUrl;
  // 替换URL中的模板变量
  url = url.replace('{{frontendPort}}', config.frontend.port);
  url = url.replace('{{backendPort}}', config.backend.port);
  
  logger.info(`正在打开浏览器: ${url}`);
  
  try {
    const platform = os.platform();
    let command;
    
    if (platform === 'win32') {
      // Windows
      command = `start "" "${url}"`;
    } else if (platform === 'darwin') {
      // macOS
      command = `open "${url}"`;
    } else {
      // Linux and others
      command = `xdg-open "${url}"`;
    }
    
    exec(command, (error) => {
      if (error) {
        logger.warn(`无法打开浏览器: ${error.message}`);
        logger.info(`请手动访问: ${url}`);
      }
    });
  } catch (error) {
    logger.warn(`无法打开浏览器: ${error.message}`);
    logger.info(`请手动访问: ${url}`);
  }
}

/**
 * 启动应用
 */
async function startApp() {
  try {
    // 显示启动信息
    const colors = {
      reset: '\x1b[0m',
      green: '\x1b[32m',
      blue: '\x1b[34m',
      yellow: '\x1b[33m'
    };
    
    logger.info('============================================');
    logger.info('            MCP 工具 - 自动启动应用           ');
    logger.info('============================================');
    
    // 如果需要，先构建项目
    if (config.global.buildBeforeStart) {
      logger.info('构建项目中...');
      buildProject();
      logger.success('项目构建完成');
    }
    
    // 先启动后端服务
    const backendStarted = await startService('backend');
    if (!backendStarted) {
      throw new Error('后端服务启动失败');
    }
    
    // 再启动前端服务
    const frontendStarted = await startService('frontend');
    if (!frontendStarted) {
      throw new Error('前端服务启动失败');
    }
    
    // 打开浏览器
    await openBrowser();
    
    // 显示成功信息
    logger.success('✅ 所有服务启动成功！');
    logger.info(`  - ${config.backend.name}: http://localhost:${config.backend.port}`);
    logger.info(`  - ${config.frontend.name}: http://localhost:${config.frontend.port}`);
    logger.info('按 Ctrl+C 停止所有服务');
    
  } catch (error) {
    logger.handleError(error, '启动应用时出错');
    stopAllServices();
    process.exit(1);
  }
}

/**
 * 简单的命令行参数解析器
 */
function parseArgs() {
  try {
    const args = process.argv.slice(2);
    const command = args[0] || 'start';
    
    // 默认选项
    const options = {
      config: null,
      build: undefined,
      browser: undefined
    };
    
    // 解析参数
    for (let i = 1; i < args.length; i++) {
      if (args[i] === '-c' || args[i] === '--config') {
        options.config = args[i + 1];
        i++;
      } else if (args[i] === '-b' || args[i] === '--build') {
        options.build = true;
      } else if (args[i] === '--no-browser') {
        options.browser = false;
      }
    }
    
    // 加载配置
    config = loadConfig(options.config);
    
    // 初始化日志
    logger = initLogger(config.logging?.level || 'info', config.logging?.filePath);
    
    // 根据命令执行不同操作
    if (command === 'start') {
      // 覆盖全局配置
      if (options.build !== undefined) {
        config.global.buildBeforeStart = options.build;
      }
      
      if (options.browser !== undefined) {
        config.global.openBrowserOnStart = options.browser;
      }
      
      // 监听退出信号
      process.on('SIGINT', () => {
        console.log('\n收到退出信号...');
        stopAllServices();
        process.exit(0);
      });
      
      // 启动应用
      startApp();
    } 
    else if (command === 'stop') {
      // 停止服务
      stopAllServices();
      process.exit(0);
    }
    else if (command === 'build') {
      // 构建项目
      buildProject();
    }
    else if (command === 'status') {
      // 检查服务状态
      checkServicesStatus();
    }
    else if (command === '-h' || command === '--help' || command === 'help') {
      showHelp();
    }
    else if (command === '-v' || command === '--version' || command === 'version') {
      showVersion();
    }
    else {
      console.log(`未知命令: ${command}`);
      showHelp();
      process.exit(1);
    }
  } catch (error) {
    // 如果logger已经初始化，使用它的handleError方法，否则使用console.error
    if (logger) {
      logger.handleError(error, '解析命令行参数时出错');
    } else {
      console.error('解析命令行参数时出错:', error.message);
    }
    process.exit(1);
  }
}

/**
 * 显示帮助信息
 */
function showHelp() {
  const colors = {
    reset: '\x1b[0m',
    green: '\x1b[32m',
    blue: '\x1b[34m',
    yellow: '\x1b[33m'
  };
  
  console.log('');
  console.log(`${colors.green}MCP (Multi-Component Project) 工具${colors.reset}`);
  console.log(`${colors.green}版本: 1.0.0${colors.reset}`);
  console.log('');
  console.log(`${colors.blue}用法: mcp [命令] [选项]${colors.reset}`);
  console.log('');
  console.log(`${colors.yellow}命令:${colors.reset}`);
  console.log('  start     启动所有服务 (默认)');
  console.log('  stop      停止所有服务');
  console.log('  build     构建项目');
  console.log('  status    检查服务状态');
  console.log('  help      显示帮助信息');
  console.log('  version   显示版本信息');
  console.log('');
  console.log(`${colors.yellow}选项:${colors.reset}`);
  console.log('  -c, --config <path>    指定配置文件路径');
  console.log('  -b, --build           启动前构建项目');
  console.log('  --no-browser          不自动打开浏览器');
  console.log('  -h, --help            显示帮助信息');
  console.log('  -v, --version         显示版本信息');
  console.log('');
  console.log(`${colors.blue}示例:${colors.reset}`);
  console.log('  mcp start              启动所有服务');
  console.log('  mcp start -b           构建后启动所有服务');
  console.log('  mcp start --no-browser 启动服务但不打开浏览器');
  console.log('  mcp stop               停止所有服务');
  console.log('  mcp build              构建项目');
  console.log('  mcp status             检查服务状态');
  console.log('');
}

/**
 * 显示版本信息
 */
function showVersion() {
  console.log('MCP (Multi-Component Project) 工具');
  console.log('版本: 1.0.0');
  console.log('');
}

/**
 * 检查服务状态
 */
async function checkServicesStatus() {
  const colors = {
    reset: '\x1b[0m',
    green: '\x1b[32m',
    red: '\x1b[31m'
  };
  
  console.log('服务状态检查:');
  console.log('-------------------');
  
  // 检查后端状态
  const backendStatus = await checkBackendHealth();
  console.log(`${config.backend.name}: ${backendStatus ? `${colors.green}运行中${colors.reset}` : `${colors.red}未运行${colors.reset}`}`);
  
  // 检查前端状态
  const frontendStatus = await checkFrontendHealth();
  console.log(`${config.frontend.name}: ${frontendStatus ? `${colors.green}运行中${colors.reset}` : `${colors.red}未运行${colors.reset}`}`);
  
  console.log('-------------------');
}

// 启动程序
parseArgs();